import 'package:flutter/material.dart';
import 'package:flutter_app/generated/l10n.dart';
import 'package:flutter_app/pages/home/loan/loan_detail.dart';
import 'package:flutter_app/pages/home/loan/loan_page.dart';
import 'package:flutter_app/pages/home/loan/myloan.dart';
import 'package:flutter_app/pages/home/loan/zero_interest_detail_page.dart';
import 'package:flutter_app/pages/notice/index.dart';
import 'package:flutter_app/pages/splash_page.dart';
import 'package:flutter_app/provider/locale_provider.dart';
import 'package:flutter_app/utils/application.dart';
import 'package:flutter_app/utils/shared_preferences.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import './pages/search_page.dart';
import './pages/set/set_page.dart';
import './pages/invest/record.dart';
import './pages/trade/record.dart';
import './pages/trade/charge.dart';
import './pages/wallet/warning.dart';

//固收
import './pages/fixedIncome/index.dart';
import './pages/fixedIncome/detail.dart';
import './pages/fixedIncome/record.dart';
import './pages/fixedIncome/buy.dart';
import './pages/fixedIncome/agreement.dart';
import './pages/my/authentication/auth_home.dart';
import './pages/my/security.dart';

//双币
import './pages/double/index.dart';
import './pages/double/list.dart';
import './pages/double/record.dart';
import './pages/double/detail.dart';
import './pages/double/buy.dart';
import './pages/double/agreement.dart';
import './pages/double/reInvest.dart';

//基金
import './pages/fund/index.dart';
import './pages/fund/hold.dart';
import './pages/fund/myInvest.dart';
import './pages/fund/detail.dart';
//杠杆
import './pages/lever/index.dart';
import './pages/lever/order.dart';
import './pages/lever/agreement.dart';

//登录
import './pages/login/index.dart';
import './pages/register/index.dart';
import './pages/forget/index.dart';

//钱包
import './pages/wallet/detail.dart';

//帮助中心
import './pages/help.dart';

//邀请好友
import './pages/my/invite_page.dart';
import './pages/invite/myInvitees.dart';
import './pages/invite/record.dart';
//会员中心
import './pages/vip/index.dart';
import './pages/vip/rule.dart';

//优惠券
import './pages/coupon/index.dart';
import './pages/coupon/invalid.dart';

//谷歌验证码
import './pages/google/step1.dart';
import './pages/google/step2.dart';
import './pages/google/step3.dart';
import 'dart:io';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/services.dart';

bool shortenOn = false;
List marketListData;
Map portfolioMap;
List portfolioDisplay;
Map totalPortfolioStats;

String upArrow = "⬆";
String downArrow = "⬇";
const double appBarHeight = 48.0;
const double appBarElevation = 1.0;
int lastUpdate;

Future<Null> getMarketData() async {
  int pages = 5;
  List tempMarketListData = [];

  Future<Null> _pullData(page) async {
    var response = await http.get(
        Uri.encodeFull(
            "https://min-api.cryptocompare.com/data/top/mktcapfull?tsym=USD&limit=100" +
                "&page=" +
                page.toString()),
        headers: {"Accept": "application/json"});

    List rawMarketListData = new JsonDecoder().convert(response.body)["Data"];
    tempMarketListData.addAll(rawMarketListData);
  }

  List<Future> futures = [];
  for (int i = 0; i < pages; i++) {
    futures.add(_pullData(i));
  }
  await Future.wait(futures);

  marketListData = [];
  // Filter out lack of financial data
  for (Map coin in tempMarketListData) {
    if (coin.containsKey("RAW") && coin.containsKey("CoinInfo")) {
      marketListData.add(coin);
    }
  }

  getApplicationDocumentsDirectory().then((Directory directory) async {
    File jsonFile = new File(directory.path + "/marketData.json");
    jsonFile.writeAsStringSync(json.encode(marketListData));
  });
  print("Got new market data.");

  lastUpdate = DateTime.now().millisecondsSinceEpoch;
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  Application.sharePreference = await SpUtil.getInstance();

  await getApplicationDocumentsDirectory().then((Directory directory) async {
    File jsonFile = new File(directory.path + "/portfolio.json");
    if (jsonFile.existsSync()) {
      portfolioMap = json.decode(jsonFile.readAsStringSync());
    } else {
      jsonFile.createSync();
      jsonFile.writeAsStringSync("{}");
      portfolioMap = {};
    }
    if (portfolioMap == null) {
      portfolioMap = {};
    }
    jsonFile = new File(directory.path + "/marketData.json");
    if (jsonFile.existsSync()) {
      marketListData = json.decode(jsonFile.readAsStringSync());
    } else {
      jsonFile.createSync();
      jsonFile.writeAsStringSync("[]");
      marketListData = [];
      // getMarketData(); ?does this work?
    }
  });
  String themeMode = "Automatic";
  bool darkOLED = false;
  SharedPreferences prefs = await SharedPreferences.getInstance();
  if (prefs.getBool("shortenOn") != null &&
      prefs.getString("themeMode") != null) {
    shortenOn = prefs.getBool("shortenOn");
    themeMode = prefs.getString("themeMode");
    darkOLED = prefs.getBool("darkOLED");
  }

  // Permission check
  Future<void> getPermission() async {
    //请求权限
    Map<Permission, PermissionStatus> statuses = await [
      Permission.storage,
      Permission.camera,
      Permission.photos
    ].request();
    if (statuses[Permission.storage] != PermissionStatus.granted) {
      Fluttertoast.showToast(
          msg: "需要打开允许访问存储权限",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.white,
          textColor: Colors.black,
          fontSize: 16.0);
      openAppSettings();
    }
    if (statuses[Permission.camera] != PermissionStatus.granted) {
      Fluttertoast.showToast(
          msg: "需要打开允许访问相机",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.white,
          textColor: Colors.black,
          fontSize: 16.0);
      openAppSettings();
    }
  }

  Future.wait([getPermission()]).then((result) {
    runApp(
      MultiProvider(
        // 接受监听
        providers: [ChangeNotifierProvider.value(value: LocaleProvider())],
        child: MyApp(themeMode, darkOLED),
      ),
    );
  });

  if (Platform.isAndroid) {
    // 设置状态栏背景及颜色
    SystemUiOverlayStyle systemUiOverlayStyle =
        SystemUiOverlayStyle(statusBarColor: Colors.transparent);
    SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
    // SystemChrome.setEnabledSystemUIOverlays([]); //隐藏状态栏
  }
}

class MyApp extends StatelessWidget {
  MyApp(this.themeMode, this.darkOLED);

  final themeMode;
  final darkOLED;

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    var localeMode = Provider.of<LocaleProvider>(context);
    return MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          // fontFamily: "dinpro",
          // This is the theme of your application.
          appBarTheme: AppBarTheme.of(context).copyWith(
            // 方式1
            brightness: Brightness.light,

            // textTheme:TextTheme(
            //   subtitle1: TextStyle(
            //     color: Colors.green,
            //     fontSize: 12,
            //   ),
            // )
          ),
          // Try running your application with "flutter run". You'll see the
          // application has a blue toolbar. Then, without quitting the app, try
          // changing the primarySwatch below to Colors.green and then invoke
          // "hot reload" (press "r" in the console where you ran "flutter run",
          // or simply save your changes to "hot reload" in a Flutter IDE).
          // Notice that the counter didn't reset back to zero; the application
          // is not restarted.
          primarySwatch: Colors.blue,
          // This makes the visual density adapt to the platform that you run
          // the app on. For desktop platforms, the controls will be smaller and
          // closer together (more dense) than on mobile platforms.
          visualDensity: VisualDensity.adaptivePlatformDensity,
        ),
        localizationsDelegates: [
          S.delegate,
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
          GlobalCupertinoLocalizations.delegate,
        ],
        // 设置中文为首选项
        supportedLocales: [
          const Locale('zh', ''),
          ...S.delegate.supportedLocales
        ],
        locale: localeMode.locale,
        builder: (BuildContext context, Widget child) {
          /// 保证文字大小不受手机系统设置影响 https://www.kikt.top/posts/flutter/layout/dynamic-text/
          return MediaQuery(
            data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
            child: child,
          );
        },
        home: SplashPage(),
        routes: {
          '/search': (BuildContext context) {
            return SearchPage();
          },
          //设置
          '/set': (BuildContext context) {
            return SetPage();
          },
          //固收
          '/fixed': (BuildContext context) {
            return FixedIncome();
          },
          //固收详情页
          '/fixed/detail': (BuildContext context) {
            return FixedDetailPage();
          },
          //购买
          '/fixed/buy': (BuildContext context) {
            return FixedBuyPage();
          },
          '/fixed/record': (BuildContext context) {
            return FixedRecordPage();
          },
          //固收产品协议
          '/fixed/agreement': (BuildContext context) {
            return FixedAgreement();
          },
          //投资记录
          '/invest/record': (BuildContext context) {
            return InvestRecordPage();
          },
          //身份认证
          '/auth/home': (BuildContext context) {
            return AuthHomePage();
          },
          //交易记录
          '/trade/record': (BuildContext context) {
            return TradeRecordPage();
          },
          //充币
          '/trade/charge': (BuildContext context) {
            return ChargePage();
          },
          //双币首页
          '/double': (BuildContext context) {
            return DoublePage();
          },
          // 双币列表
          '/double/list': (BuildContext context) {
            return DoubleListPage();
          },
          //  双币-投资记录
          '/double/record': (BuildContext context) {
            return DoubleRecordPage();
          },
          //双币-详情
          '/double/detail': (BuildContext context) {
            return DoubleDetailPage();
          },
          //双币-购买
          '/double/buy': (BuildContext context) {
            return DoubleBuyPage();
          },
          //  投资协议
          '/agreement': (BuildContext context) {
            return Agreement();
          },
          //  双币复投
          '/double/reinvest': (BuildContext context) {
            return ReInvestPage();
          },
          //  基金
          '/fund': (BuildContext context) {
            return FundPage();
          },
          '/fund/hold': (BuildContext context) {
            return FundHoldPage();
          },
          '/fund/invest': (BuildContext context) {
            return MyFundInvest();
          },
          '/fund/detail':(BuildContext context){
            return FundDetailPage();
          },
          //  杠杆
          '/lever': (BuildContext context) {
            return LeverPage();
          },
          '/lever/order': (BuildContext context) {
            return LeverOrderPage();
          },
          '/lever/agreement': (BuildContext context) {
            return AgreementPage();
          },
          // 登录
          '/login': (BuildContext context) {
            return LoginPage();
          },
          '/reg': (BuildContext context) {
            return RegisterPage();
          },
          '/forget': (BuildContext context) {
            return ForgetPage();
          },
          //钱包
          '/wallet/detail': (BuildContext context) {
            return WalletDetailPage();
          },
          //账户安全
          '/safe': (BuildContext context) {
            return SecurityPage();
          },
          //  安全提示
          '/safe/warning': (BuildContext context) {
            return WarningPage();
          },
          //借贷
          '/loan': (BuildContext context) {
            return LoanPage();
          },
          //借贷详情页
          '/loan/detail':(BuildContext context){
             return LoanDetailPage();
          },
          //我的借贷
          '/loan/my':(BuildContext context){
             return MyloanPage();
          },
          //零息借贷详情
          '/loan/zero/detail':(BuildContext context){
            return ZeroInterestDetail();
          },
          '/help': (BuildContext context) {
            return HelpPage();
          },
          //邀请
          '/invite': (BuildContext context) {
            return InvitePage();
          },
          '/invite/invitee':(BuildContext context){
            return MyInviteesPage();
          },
          '/invite/record':(BuildContext context){
            return InviteRecordPage();
          },
          //  会员中心
          '/vip': (BuildContext context) {
            return VipPage();
          },
          '/vip/rule': (BuildContext context) {
            return RulePage();
          },
          '/coupon': (BuildContext context) {
            return CouponsPage();
          },
          '/coupon/invalid': (BuildContext context) {
            return InvalidCouponsPage();
          },
          //  公告
          '/notice': (BuildContext context) {
            return NoticePage();
          },
          // 谷歌
          '/google/step1': (BuildContext context) {
            return GoogleStep1();
          },
          '/google/step2': (BuildContext context) {
            return GoogleStep2();
          },
          '/google/step3': (BuildContext context) {
            return GoogleStep3();
          },
        });
  }
}

numCommaParse(numString) {
  if (shortenOn) {
    String str = num.parse(numString ?? "0")
        .round()
        .toString()
        .replaceAllMapped(new RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))'),
            (Match m) => "${m[1]},");
    List<String> strList = str.split(",");

    if (strList.length > 3) {
      return strList[0] +
          "." +
          strList[1].substring(0, 4 - strList[0].length) +
          "B";
    } else if (strList.length > 2) {
      return strList[0] +
          "." +
          strList[1].substring(0, 4 - strList[0].length) +
          "M";
    } else {
      return num.parse(numString ?? "0").toString().replaceAllMapped(
          new RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))'), (Match m) => "${m[1]},");
    }
  }

  return num.parse(numString ?? "0").toString().replaceAllMapped(
      new RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))'), (Match m) => "${m[1]},");
}

normalizeNum(num input) {
  if (input == null) {
    input = 0;
  }
  if (input >= 100000) {
    return numCommaParse(input.round().toString());
  } else if (input >= 1000) {
    return numCommaParse(input.toStringAsFixed(2));
  } else {
    return input.toStringAsFixed(6 - input.round().toString().length);
  }
}

normalizeNumNoCommas(num input) {
  if (input == null) {
    input = 0;
  }
  if (input >= 1000) {
    return input.toStringAsFixed(2);
  } else {
    return input.toStringAsFixed(6 - input.round().toString().length);
  }
}
